<?php
/**
 *  找回密码服务
*/

namespace app\api\service;

use app\facade\Basic;
use app\api\model\Customer;
use think\facade\Config;


class Retrieve
{

    /**
     *  获取邮箱验证
    */
    public function getEmailCode($param)
    {

        $result = Customer::where('email',$param['email'])->find();

        if(!$result){
            return Basic::data(1,'retrieve.emailDoesNotExist');
        }

        $data['code'] = getVerifyCode(6);
        $data['to'] = $result->email;
        $data['subject'] = 'get Email Code';
        $content = <<<HTML
     code: {$data['code']}
HTML;
        $data['content'] = $content;
        return MailCheck::create($data);
    }

    /**
     *  重置密码
    */
    public function password($param)
    {

        /* 验证验证码 */
        if ( !$param['code'] ) {
            return Basic::data(1,'retrieve.verificationCodeNotExist');
        }


        if ( !$code = MailCheck::check($param) ){
            return Basic::data(1,'retrieve.verificationCodeError');
        }

        if ( $param['code'] != $code ){
            return Basic::data(1,'retrieve.verificationCodeError');
        }


        /* 邮箱验证码 */
        $result = Customer::where('email',$param['email'])->find();
        if(!$result){
            return Basic::data(1,'retrieve.emailDoesNotExist');
        }

        /* 修改密码 */
        $password_salt = Config::get('api.password_salt');
        $create_time = $result->create_time;
        $password = $param['password'];
        $result->password = md5(md5($password.$password_salt.$create_time));

        /* 保存 */
        if ( $result->save() ){
            return Basic::data(0,'retrieve.passwordResetSuccessful');
        } else {
            return Basic::data(1,'retrieve.passwordResetFailed');
        }

    }


}